<template>
    <div
        ref="main"
        class="text-scroll"
        :style="styleComputed"
        @mouseenter="moveText()"
        @mouseleave="reset()"
    >
        <span
            ref="content"
            class="text-scroll__name"
            v-html="title"
        ></span>
    </div>
</template>
<script>
export default {
    name: 'text-scroll',
    props: {
        cursor: {
            type: Boolean,
            default: true,
        },
        title: {
            type: String,
            default: '',
        },
        parentWidth: {
            type: [Number, String],
            default: 0,
        },
        titleClass: {
            type: [Array, String],
            default: '',
        },
    },
    data() {
        return {
            stopMotion: false,
        };
    },
    computed: {
        styleComputed() {
            let obj = {
                cursor: this.cursor ? 'pointer' : 'default',
            };
            if (this.parentWidth) {
                obj.width = this.parentWidth + 'px';
            }
            return obj;
        },
    },
    methods: {
        moveText() {
            const content = this.$refs.content;
            const childWidth = content.offsetWidth;
            const parentWidth = this.parentWidth || this.$refs.main.offsetWidth;
            const speed = 0.5;
            let translate = 0;
            let overflowLen = childWidth - parentWidth;
            this.stopMotion = false;

            const _this = this;
            let animation = function () {
                requestAnimationFrame(() => {
                    if (_this.stopMotion) return;

                    if (overflowLen > 0) {
                        animation();

                        content.style.cssText = `transform: translateX(-${translate}px);`;
                        translate = translate + speed;
                        overflowLen = overflowLen - speed;
                    }
                });
            };
            animation();
        },
        reset() {
            this.stopMotion = true;
            const content = this.$refs.content;
            content.style.cssText = 'transform: translateX(0px);';
        },
    },
};
</script>
<style>
.text-scroll {
    overflow: hidden;
    width: 100%;
}
.text-scroll__name {
    display: inline-block;
    white-space: nowrap;
}
</style>
